//
//  MediaEditViewController.m
//  XPhoto
//
//  Created by baboy on 2019/2/20.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "MediaEditViewController.h"
#import "MediaEditTableViewCell.h"
#import "MediaEditPhotoCell.h"
#import "MediaEditContentCell.h"
#import "SerialSearchViewController.h"
#import "BKNavigationController.h"
#import "PhotoEditPreviewViewController.h"
#import "BKActionSheet.h"
#import "PhotoLibViewController.h"
#import "PhotoCameraViewController.h"
#import "TagSearchViewController.h"
#import "AddrSearchViewController.h"
#import "Post.h"
#import "UIViewController+camera.h"
#import "TagTableViewCell.h"
#import <AssetsLibrary/AssetsLibrary.h>


#define TABLE_ROW_CONTENT_INDEX 0
#define TABLE_ROW_PREVIEW_INDEX 1
#define TABLE_ROW_ADDR_INDEX 2
#define TABLE_ROW_TAG_INDEX 3
#define TABLE_ROW_SERIAL_INDEX 4
#define TABLE_ROW_STATUS_INDEX 5



@interface MediaEditViewController ()<PhotoEditPreviewDelegate, PhotoEditDelegate,PhotoLibViewDelegate,BKActionSheetDelegate,SerialSearchDelegate, TagSearchDelegate, AddrSearchDelegate>
@property(nonatomic, strong) TagTableViewCell *tagCell;
@property(nonatomic, strong) MediaEditPhotoCell *photoCell;
@property(nonatomic, strong) MediaEditContentCell *contentCell;
@property(nonatomic, strong) PostSerial *serial;
@property(nonatomic, strong) BKPlace *place;
@property(nonatomic, strong) NSArray *tags;
@property(nonatomic, strong) NSArray *serials;
@property(nonatomic, strong) Post *post;
@property(nonatomic, strong) CLLocation *photoLocation;

@end

@implementation MediaEditViewController
- (id)init{
    if (self = [super initWithNibName:NSStringFromClass([self class]) bundle:nil]){
        _post = [Post new];
    }
    return self;
}
- (id)initWithPhotos:(NSArray *)photos{
    if (self = [self init]) {
        _photos = [NSMutableArray arrayWithArray:photos];
        for (PhotoAsset *photoAsset in _photos) {
            if(photoAsset.asset){
                self.photoLocation = photoAsset.asset.location;
                self.post.createTime = photoAsset.asset.creationDate;
                DLOG(@"post create at:%@, %f, %f", self.post.createTime, self.photoLocation.coordinate.latitude, self.photoLocation.coordinate.longitude);
                break;
            }
        }
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    self.tags = @[@"中华人民共和国", @"新型冠状病毒肺炎COVID-19", @"朝阳群众", @"孩子",@"标签写实Test"];
    self.title = NSLocalizedString(@"edit", nil);
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"back", @"按钮") style:UIBarButtonItemStylePlain target:self action:@selector(goBack:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"send", @"按钮")
                                                                              style:UIBarButtonItemStyleDone
                                                                             target:self
                                                                             action:@selector(send:)];
}
- (void)setPhotos:(NSMutableArray *)photos{
    _photos = [NSMutableArray arrayWithArray:photos];
}
#pragma mark - UITableViewDelegate
- (MediaEditPhotoCell*)photoCell{
    if (!_photoCell) {
        _photoCell = (MediaEditPhotoCell*) loadViewFromNib([MediaEditPhotoCell class], self);
        _photoCell.delegate = self;
    }
    return _photoCell;
}
- (MediaEditContentCell*)contentCell{
    if (!_contentCell) {
        _contentCell = loadViewFromNib([MediaEditContentCell class], self);
    }
    return _contentCell;
}
- (TagTableViewCell*)tagCell{
    if (!_tagCell) {
        _tagCell = loadViewFromNib([TagTableViewCell class], self);
    }
    return _tagCell;
}
- (NSArray *)selectedSerialTitles{
    NSMutableArray *titles = [NSMutableArray array];
    for (NSInteger i = 0, n = self.serials.count; i < n; i++) {
        PostSerial *serial = [self.serials objectAtIndex:i];
        [titles addObject:serial.title];
    }
    return titles.count > 0 ? titles : nil;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 6;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    DLOG(@"+++++++++++%ld", indexPath.row);
    switch (indexPath.row) {
        case TABLE_ROW_CONTENT_INDEX:{
            return 88;
        }
        case TABLE_ROW_PREVIEW_INDEX:{
            CGFloat h = [MediaEditPhotoCell heightWithPhotos:self.photos cellWidth:self.view.bounds.size.width shouldTakePhoto:[self maxSelectedPhotoCount]>0];
            return h;
        }
        case TABLE_ROW_TAG_INDEX:/*{
            CGFloat h = [self.tagCell heightWithTags:self.tags cellWidth:self.tableView.bounds.size.width];
            return h;
        }*/
        case TABLE_ROW_ADDR_INDEX:
        case TABLE_ROW_SERIAL_INDEX:
        case TABLE_ROW_STATUS_INDEX:{
            self.tagCell.tags = self.tags;
            return UITableViewAutomaticDimension;
        }
        default:
            break;
    }
    return 0;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DLOG(@"--------------%ld", indexPath.row);
    if (indexPath.row == TABLE_ROW_CONTENT_INDEX) {
        return self.contentCell;
    }
    if (indexPath.row == TABLE_ROW_PREVIEW_INDEX) {
        self.photoCell.photos = self.photos;
        return self.photoCell;
    }
    if (indexPath.row == TABLE_ROW_TAG_INDEX) {
        self.tagCell.titleLabel.text = NSLocalizedString(@"tag", @"标签");
        self.tagCell.tags = self.tags;
        return self.tagCell;
    }
    
    if (indexPath.row == TABLE_ROW_SERIAL_INDEX ) {
        TagTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([TagTableViewCell class])];
        if (!cell) {
            cell = loadViewFromNib([TagTableViewCell class], nil);
        }
        cell.titleLabel.text = NSLocalizedString(@"serial", @"标签");
        cell.tags = [self selectedSerialTitles];
        return cell;
        
//        cell.detailLabel.text = self.serial.title;
//        cell.instructionButton.hidden = NO;
//        [cell.instructionButton setTitle:NSLocalizedString(@"查看说明", @"按钮") forState:UIControlStateNormal];
//        [cell.instructionButton addTarget:self action:@selector(viewSerialInstruction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    MediaEditTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MediaEditTableViewCell class])];
    if(!cell){
        cell = loadViewFromNib([MediaEditTableViewCell class], self);
    }
    cell.instructionButton.hidden = YES;
    if (indexPath.row == TABLE_ROW_ADDR_INDEX) {
        cell.titleLabel.text =  NSLocalizedString(@"addr", @"标签");
        cell.detailLabel.text = self.post.addr;
    }
    if(indexPath.row == TABLE_ROW_STATUS_INDEX){
        cell.titleLabel.text = NSLocalizedString(@"public", @"标签");
        if (!_policySwitch) {
            _policySwitch = [[UISwitch alloc] init];
            _policySwitch.on = YES;
        }
        cell.accessoryView = self.policySwitch;
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    id vc = nil;
    switch (indexPath.row) {
        case TABLE_ROW_ADDR_INDEX:{
            vc = [[AddrSearchViewController alloc] init];
            if (self.photoLocation) {
                [vc setLocation:self.photoLocation];
            }
            [vc setDelegate:self];
            break;
        }
        case TABLE_ROW_TAG_INDEX:{
            vc = [[TagSearchViewController alloc] init];
            
            ((TagSearchViewController*)vc).maxSelectedCount = 5;
            ((TagSearchViewController*)vc).tags = [NSMutableArray arrayWithArray:self.tags];
            ((TagSearchViewController*)vc).delegate = self;
            break;
        }
        case TABLE_ROW_SERIAL_INDEX:{
            vc = [SerialSearchViewController new];
            ((SerialSearchViewController*)vc).delegate = self;
            ((SerialSearchViewController*)vc).selectedItems = [NSMutableArray arrayWithArray:self.serials];
            break;
        }
        default:
            break;
    }
    if (vc) {
        UINavigationController *nav = [[BKNavigationController alloc] initWithRootViewController:vc];
        nav.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:nav animated:YES completion:^{
            
        }];
    }
}
- (void)goBack:(id)button{
    [self dismissViewControllerAnimated:YES
                             completion:^{
                                 
                             }];
}
#pragma MediaEditPhotoCell delegate

- (NSInteger)maxSelectedPhotoCount{
    return 5 - self.photos.count;
}
- (void)previewCell:(id)cell addPhoto:(id)button{
    [self takePhoto];
}
- (void)previewCell:(id)cell clickPhotoView:(id)photoView{
    PhotoEditPreviewViewController *vc = [[PhotoEditPreviewViewController alloc] initWithPhotos:self.photoCell.photos];
    vc.delegate = self;
    vc.defaultPage = [(UIView*)photoView tag];
    BKNavigationController *nav = [[BKNavigationController alloc] initWithRootViewController:vc];
    nav.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:nav animated:YES
                     completion:^{
                         
                     }];
}
#pragma MediaEditPreviewDelegate
- (PhotoAsset *)photoAssetWithIdentifier:(NSString *)identifier{
    for (PhotoAsset *photoAsset in self.photos) {
        if ([photoAsset.asset.localIdentifier isEqualToString:identifier]) {
            return photoAsset;
        }
    }
    return nil;
}
- (void)previewViewController:(id)viewController didRemovePhoto:(PhotoAsset*)photo{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:TABLE_ROW_PREVIEW_INDEX inSection:0];
    PhotoAsset *existPhotoAsset = [self photoAssetWithIdentifier:photo.asset.localIdentifier];
    [self.photos removeObject:existPhotoAsset];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//    [self.tableView reloadData];
}

#pragma add new photos
- (void)photoLibViewController:(id)photoLibViewController didSelectPhotos:(NSArray<PhotoAsset *> *)photoAssets{
    DLOG(@"%@",photoAssets);
    if (photoAssets && photoAssets.count>0) {
        for (PhotoAsset *photoAsset in photoAssets) {
            PhotoAsset *existPhotoAsset = [self photoAssetWithIdentifier:photoAsset.asset.localIdentifier];
            if (!existPhotoAsset) {
                [self.photos addObject:photoAsset];
            }
            if (existPhotoAsset) {
                [BKIndicator showTips:NSLocalizedString(@"photo_exists", @"提示")
                               inView:self.view
                             duration:2.0f
                           completion:nil];
            }
        }
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:TABLE_ROW_PREVIEW_INDEX inSection:0]]
                              withRowAnimation:UITableViewRowAnimationNone];
    }
}
- (void)serialSearchViewController:(id)vc didSelectSerials:(nonnull NSArray<PostSerial *> *)serials{
    self.serials = serials;
    NSMutableArray *serialIds = [NSMutableArray array];
    for (NSInteger i = 0, n = serials.count; i<n; i++) {
        PostSerial *serial = [serials objectAtIndex:i];
        [serialIds addObject:@(serial.id)];
    }
    self.post.serialIds = serialIds;
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:TABLE_ROW_SERIAL_INDEX inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}
- (void)tagSearchViewController:(id)controller didSearchTags:(NSArray *)tags{
    self.tags = tags;
    self.post.tags = tags;
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:TABLE_ROW_TAG_INDEX inSection:0]]
                          withRowAnimation:UITableViewRowAnimationNone];
}
- (void)addrSearchViewController:(id)controller didSelectPlace:(BKPlace*)place{
    self.place = place;
    self.post.addr = place.name;
    self.post.lat = self.place.lat;
    self.post.lng = self.place.lng;
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:TABLE_ROW_ADDR_INDEX inSection:0]]
                          withRowAnimation:UITableViewRowAnimationNone];
}

#pragma mark - submit data
- (void)send:(id)btn{
    self.post.content = self.contentCell.contentTextView.text;
    self.post.policy = self.policySwitch.isOn ? 1 : 0;
    self.post.type = RECORD_TYPE_PHOTO;
    NSMutableArray *items = [NSMutableArray array];
    for(NSInteger i = 0, n = self.photos.count; i< n; i++){
        PhotoAsset *photoAsset = [self.photos objectAtIndex:i];
        PostItem *item = [PostItem new];
        item.type = RECORD_TYPE_PHOTO;
        if (photoAsset.asset.mediaType == PHAssetMediaTypeVideo) {
            item.type = RECORD_TYPE_VIDEO;
            self.post.type = RECORD_TYPE_PHOTO;
        }
        item.width = photoAsset.width;
        item.height = photoAsset.height;
        item.url = photoAsset.originPath;
        item.thumb = photoAsset.thumbPath;
        [items addObject:item];
    }
    self.post.items = items;
    
    [Post create:self.post
          photos:self.photos
photoUploadProgress:^(NSString * _Nonnull key, float p) {
        
    }
      completion:^{
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_POST_PUBLISHED object:nil userInfo:@{@"post":self.post}];
    }];
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewSerialInstruction:(UIButton *)button{
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
